package com.whfc.mach.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.util.DateUtil;
import com.whfc.fuum.dto.SysDeptDTO;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.mach.dao.AppMachDayMapper;
import com.whfc.mach.dao.AppMachMonthMapper;
import com.whfc.mach.dto.AppMachDataStatDTO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 设备每月运行数据计算任务
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/29 16:46
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class MachMonthDataStatJob {
    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @Autowired
    private AppMachDayMapper machDayMapper;

    @Autowired
    private AppMachMonthMapper machMonthMapper;

    /**
     * 每月1号凌晨2点30开始统计设备每月数据
     */
    @XxlJob("statMachMonthData")
    public void statMachMonthData() {
        XxlJobHelper.log("定时任务统计设备每月数据");
        Date yestody = DateUtil.addDays(new Date(), -1);
        Date monthBegin = DateUtil.getMonthBegin(yestody);
        Date monthEnd = DateUtil.getMonthEnd(yestody);
        List<SysDeptDTO> deptList = sysDeptService.getAllProjectList();
        if (deptList.size() > 0) {
            List<Integer> errorId = new ArrayList<>();
            for (SysDeptDTO sysDept : deptList) {
                try {
                    List<Integer> deptIds = sysDeptService.getDescendantDeptIdList(sysDept.getId());
                    if (deptIds == null || deptIds.size() == 0) {
                        continue;
                    }
                    XxlJobHelper.log("统计设备每月数据服务,deptIds:{},monthBegin:{},monthEnd:{}", deptIds, monthBegin, monthEnd);
                    List<AppMachDataStatDTO> list = machDayMapper.selectAvgDataByDeptIds(deptIds, monthBegin, monthEnd);
                    if (list.size() == 0) {
                        return;
                    }
                    machMonthMapper.batchInsert(DateUtil.formatDate(monthBegin, "yyyy-MM"), list);
                } catch (Exception e) {
                    XxlJobHelper.log("deptId:{},定时任务统计设备每月数据失败,{}", sysDept.getId(), e.getMessage());
                    errorId.add(sysDept.getId());
                    continue;
                }
            }
            if (!errorId.isEmpty()) {
                XxlJobHelper.handleFail("定时任务统计设备每月数据失败，失败id：" + JSONObject.toJSONString(errorId));
            }

        }
    }
}
